package com.jimmy.medical.util;

import com.jimmy.medical.model.AjaxResult;
import com.jimmy.medical.model.PageRequestParam;
import com.jimmy.medical.model.PageResponseResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * Ajax工具类
 */
public class AjaxUtils {
    /**
     * 处理ajax结果
     *
     * @param action
     * @param <T>
     * @return
     */
    public static <T> AjaxResult<T> process(Func_T<T> action) {
        AjaxResult<T> ajaxResult = new AjaxResult<T>();
        ajaxResult.setSuccess(false);
        try {
            T result = action.invoke();
            ajaxResult.setSuccess(true);
            ajaxResult.setData(result);
        } catch (Exception e) {
            ajaxResult.setMessage(e.getMessage());
        }

        return ajaxResult;
    }

    /**
     * 处理列表ajax结果
     *
     * @param page
     * @param action
     * @param <T>
     * @return
     */
    public static <T> PageResponseResult<T> processPage(PageRequestParam page, Func_T1<PageRequest, Page<T>> action) {
        PageResponseResult<T> pageResult = new PageResponseResult<T>();
        pageResult.setCode(-1);
        try {
            PageRequest pageable = new PageRequest(page.getPage() - 1, page.getLimit());
            Page<T> pageList = action.invoke(pageable);
            pageResult.setCode(0);
            pageResult.setCount(pageList.getTotalElements());
            pageResult.setData(pageList.getContent());
        } catch (Exception e) {
            pageResult.setMsg(e.getMessage());
        }

        return pageResult;
    }

    public static <T> PageResponseResult<T> processPage(PageRequestParam page, Sort sort, Func_T1<PageRequest, Page<T>> action) {
        PageResponseResult<T> pageResult = new PageResponseResult<T>();
        pageResult.setCode(-1);
        try {
            PageRequest pageable = new PageRequest(page.getPage() - 1, page.getLimit(),sort);
            Page<T> pageList = action.invoke(pageable);
            pageResult.setCode(0);
            pageResult.setSuccess(1);

            pageResult.setCount(pageList.getTotalElements());
            pageResult.setData(pageList.getContent());
        } catch (Exception e) {
            pageResult.setMsg(e.getMessage());
        }

        return pageResult;
    }
}
